﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Text;

namespace Universe.SimpleQueue.Samples
{
    public class DDLResources
    {

        public static readonly string SqlDdlName = "MSSQL.DDL.sql";
        public static readonly string SqlCeDdlName = "MSSQLCE.DDL.sql";

        public static List<string> MSSQLDDL
        {
            get { return ReadFile(SqlDdlName); }
        }

        public static List<string> MSSQLCEDDL
        {
            get { return ReadFile(SqlCeDdlName); }
        }

        public static void ApplyDDL(DbConnection con, string key)
        {
            var all = ReadFile(key);
            foreach (var s in all)
            {
                var cmd = con.CreateCommand();
                cmd.CommandText = s;
                cmd.CommandType = CommandType.Text;
                Trace.WriteLine(Environment.NewLine + s);
                cmd.Connection = con;
                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    var hahaha = "continue";
                    Trace.WriteLine("Fail" + ex);
                }
            }
        }

        static List<string> ReadFile(string key)
        {
            var a = Assembly.GetExecutingAssembly();
            var s = a.GetManifestResourceStream(typeof (DDLResources), key);
            if (s == null)
                throw new InvalidOperationException("Embedded resource '" + typeof(DDLResources).Namespace + "." + key + " is expected");

            List<string> ret = new List<string>();
            StringBuilder next = new StringBuilder();
            using (StreamReader rdr = new StreamReader(s, Encoding.UTF8))
            {
                string row;
                while ((row = rdr.ReadLine()) != null)
                {
                    if (row.Equals("GO", StringComparison.CurrentCultureIgnoreCase))
                    {
                        ret.Add(next.ToString());
                        next.Clear();
                    }
                    else
                        next.AppendLine(row);
                }
            }

            if (next.Length > 0)
                ret.Add(next.ToString());

            return ret;
        }

    }
}
